<?php

namespace app\common\logic;

use think\Cache;
use think\Db;
use think\Exception;

class ExchangeScoresLogic extends Logic
{
    static public function process()
    {
        $user_comment = Db::name('user_comment');
        $user_scores_db = Db::name('user_scoreslog');
        $user_db = Db::name('user');

        $start_time = time() - 86400 * 7;

        $exist_ids = $user_scores_db->where([
            'type' => 1,
            'add_time' => ['egt', $start_time],
        ])->column('f_key');

        $list = $user_comment->where([
            'add_time' => ['egt', $start_time],
            'is_check' => 1,
            'id' => ['not in', $exist_ids],
        ])->select();

        $scores = config('project.comment_scores');

        foreach ($list as $v) {
            $id = $user_scores_db->where('f_key', $v['id'])->value('id');
            if ($id > 0) continue;

            $u_scores = $user_db->where('id', $v['uid'])->value('scores');

            Db::startTrans();
            //添加积分记录
            $scores_result = $user_scores_db->insert([
                'uid' => $v['uid'],
                'type' => 1,
                'affect_scores' => $scores,
                'account_scores' => $u_scores + $scores,
                'info' => '评论赢积分',
                'f_key' => $v['id'],
                'add_time' => time(),
            ]);

            //更加个人积分
            $user_result = $user_db->where('id', $v['uid'])->setInc('scores', $scores);

            if ($scores_result && $user_result) {
                Db::commit();
            } else {
                Db::rollback();
            }

        }
    }

    static function update_course_buy()
    {
        $user_order_db = Db::name('user_order');
        $course_db = Db::name('course');

        $list = $user_order_db->where('is_read', 0)->field('id,course_id')->limit(0, 5)->select();
        foreach ($list as $v) {
            $user_order_db->where('id', $v['id'])->update(['is_read' => 1]);

            $course_db->where('id', $v['course_id'])->setInc('count');
        }
    }
}